extends Node

signal _on_connected_event(id: int)
signal _on_authenticating(id: int)
signal _on_disconnected_event(id: int)
signal _on_authentication_failed(id: int)

var peer : ENetMultiplayerPeer = ENetMultiplayerPeer.new()
var _auth_callback : Callable

func _ready() -> void:
	peer.create_server(25003)

func _create_multiplayer(_multiplayer : MultiplayerAPI) -> void :
	_multiplayer.auth_callback = _on_peer_auth_callback.bind(_multiplayer)
	_multiplayer.peer_connected.connect(_on_peer_connected_event)
	_multiplayer.peer_disconnected.connect(_on_peer_disconnected_event)
	_multiplayer.peer_authenticating.connect(_on_peer_authenticating)
	_multiplayer.peer_authentication_failed.connect(_on_peer_authentication_failed)

func _set_multiplayer(_multiplayer : MultiplayerAPI) -> void :
	_multiplayer.multiplayer_peer = peer

func _on_peer_connected_event(id: int) -> void :
	print("玩家：",id,"成功连接")
	_on_connected_event.emit(id)

func _on_peer_disconnected_event(id: int) -> void :
	print("玩家：",id,"断开连接")
	_on_disconnected_event.emit(id)

func _on_peer_authenticating(id: int) -> void :
	print("玩家：",id,"申请鉴权")
	_on_authenticating.emit(id)

func _on_peer_auth_callback(id: int, data: PackedByteArray, _multiplayer: MultiplayerAPI) :
	assert(data.size()>0,"玩家："+str(id)+"鉴权数据请求为空，有疑似攻击嫌疑，请注意监控!!!")
	var str_data = data.get_string_from_utf8()
	var json = JSON.new()
	assert(json.parse(str_data)==OK and is_same(typeof(json.data),TYPE_DICTIONARY),"玩家："+str(id)+"鉴权数据："+str_data+",无法转换为可读数据，有疑似攻击嫌疑，请注意监控!!!")
	var raw_data = JSON.parse_string(str_data)
	if _auth_callback :
		print("玩家：",id,"鉴权开始，请求数据：",raw_data)
		if _auth_callback.call(id, raw_data) : _multiplayer.complete_auth(id)
	else :
		printerr("多人网络组件未设置鉴权回调函数！！！！！")

func _on_peer_authentication_failed(id: int) -> void :
	print("玩家：",id,"鉴权失败")
	_on_authentication_failed.emit(id)
